﻿using UnityEngine;
using UnityEngine.EventSystems;

public class DragableUI : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    public Camera UICamera;
    private Vector3 offset;

    public void OnBeginDrag(PointerEventData eventData)
    {
        if (RectTransformUtility.ScreenPointToWorldPointInRectangle(GetComponent<RectTransform>(), eventData.position,
                UICamera, out var worldPoint))
            //获取鼠标的偏移量
            offset = GetComponent<RectTransform>().position - worldPoint;
    }

    public void OnDrag(PointerEventData eventData)
    {
        if (RectTransformUtility.ScreenPointToWorldPointInRectangle(GetComponent<RectTransform>(), eventData.position,
                UICamera, out var worldPoint))
            //修正
            GetComponent<RectTransform>().position = offset + worldPoint;
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        offset = Vector3.zero;
    }
}